import axios from 'axios';
import { Message } from 'element-ui';
import store from './../store';
import router from './../router';

const _config = {
    host: 'https://service.iwunulock.cn',
    port: '',
    base: ''
};


// 由前面的config拼接而成
const Api = {
    getImgList: '/fackLock/admin/iot/facesList',
    delFaces: '/fackLock/admin/iot/delFaces',
    saveFaces: '/fackLock/admin/iot/facesImage',    // 下发
    updateFaceTime: '/fackLock/admin/iot/updateFace',   // 延时
    getLogList: '/fackLock/admin/iot/loglist'
};

const instance = axios.create({
    baseURL: _config.port ? `${_config.host}:${_config.port}${_config.base}` : _config.host,
    timeout: 10000,
    transformRequest: [],
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    },
});
instance.interceptors.request.use(function(config){
    let token = store.state.token || window._$cookie.get('wn_token');
    if( token ) config.headers.Authorization = token;
    var headers = config.headers;
    var multipart = headers['Content-Type'] == 'multipart/form-data'
    if(multipart==false &&config.method === 'post') {
        config.data = JSON.stringify(config.data);
    }
    // console.warn(config);
    return config;
});

instance.interceptors.response.use(response=>{
    return new Promise((resolve, reject)=>{
        let data = response.data,
            status = Number(data.code);
        if( status === 1000 ) resolve(data);
        else if( status === 401 ) router.push({name: 'login'});
        else reject(data);
    });
}, error=>{ // 请求未到达服务器
    console.info(error);
    Message.error({
        showClose: true,
        message: '请求服务器失败',
        type: 'error'
    });
});


function httpGet(url, params, headers){
    return new Promise((resolve, reject)=>{
        instance.get(url, {params, headers}).then(resolve)
        .catch((err)=>{
            Message.error({
                showClose: true,
                message: err.msg || '获取数据错误',
                type: 'error'
            });
        });
    });
}

function httpPost(url, data = {}, headers){
    return new Promise((resolve, reject)=>{
        instance.post(url, data, {headers}).then(resolve)
        .catch((err)=>{
            Message.error({
                showClose: true,
                message: err.msg || '获取数据错误',
                type: 'error'
            });
        });
    });
}

export default {
    Api,
    instance,
    httpGet,
    httpPost
}